/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * Copyright (C) 2016-2020 the AndroidAnnotations project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.holder;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JExpr;
import com.helger.jcodemodel.JInvocation;
import com.helger.jcodemodel.JMethod;
import com.helger.jcodemodel.JVar;

import org.ohosannotations.OhosAnnotationsEnvironment;

import java.util.ArrayList;
import java.util.List;

import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;

import static com.helger.jcodemodel.JMod.PRIVATE;
import static com.helger.jcodemodel.JMod.PUBLIC;
import static javax.lang.model.element.ElementKind.CONSTRUCTOR;
import static org.ohosannotations.helper.ModelConstants.generationSuffix;

/**
 * ereceiver持有人
 *
 * @author dev
 * @since 2021-07-22
 */
public class EReceiverHolder extends EComponentHolder {
    private JBlock onReceiveBody;
    private JVar onReceiveIntentAction;
    private JVar onReceiveIntentDataScheme;
    private JVar onReceiveData;
    private JMethod onReceiveMethod;

    /**
     * ereceiver持有人
     *
     * @param environment 环境
     * @param annotatedElement 带注释的元素
     * @throws Exception 异常
     */
    public EReceiverHolder(OhosAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception {
        super(environment, annotatedElement);
        createConstructor();
    }

    /**
     * 设置上下文裁判
     */
    @Override
    protected void setContextRef() {
        if (init == null) {
            setInit();
        }
    }

    /**
     * 设置初始化
     */
    @Override
    protected void setInit() {
        init = generatedClass.method(PRIVATE, getCodeModel().VOID, "init" + generationSuffix());
        contextRef = init.param(getClasses().CONTEXT, "context");
        if (onReceiveMethod == null) {
            createOnReceive();
        }
    }

    /**
     * 创建构造函数
     */
    private void createConstructor() {
        List<ExecutableElement> constructors = new ArrayList<>();
        for (Element element : annotatedElement.getEnclosedElements()) {
            if (element.getKind() == CONSTRUCTOR) {
                constructors.add((ExecutableElement) element);
            }
        }

        for (ExecutableElement userConstructor : constructors) {
            JMethod copyConstructor = generatedClass.constructor(PUBLIC);

            JBlock body = copyConstructor.body();
            JInvocation superCall = body.invoke("super");
            AbstractJClass narrowedGeneratedClass = narrow(generatedClass);

            JInvocation newInvocation = JExpr._new(narrowedGeneratedClass);
            for (VariableElement param : userConstructor.getParameters()) {
                String paramName = param.getSimpleName().toString();
                AbstractJClass paramType = codeModelHelper.typeMirrorToJClass(param.asType());
                copyConstructor.param(paramType, paramName);
                superCall.arg(JExpr.ref(paramName));
                newInvocation.arg(JExpr.ref(paramName));
            }
        }
    }

    /**
     * 创建在接收
     */
    private void createOnReceive() {
        onReceiveMethod = generatedClass.method(PUBLIC, getCodeModel().VOID, "onReceiveEvent");
        onReceiveData = onReceiveMethod.param(getClasses().COMMON_EVENT_DATA, "commonEventData");
        onReceiveMethod.annotate(Override.class);
        onReceiveBody = onReceiveMethod.body();
        onReceiveBody.invoke(JExpr._super(), onReceiveMethod).arg(onReceiveData);
    }

    /**
     * 设置接收意图行动
     */
    private void setOnReceiveIntentAction() {
        JInvocation getActionInvocation = JExpr.invoke(getOnReceiveData(), "getIntent").invoke("getAction");
        onReceiveIntentAction = getOnReceiveBody().decl(getClasses().STRING, "action", getActionInvocation);
    }

    /**
     * 设置接收意图数据计划
     */
    private void setOnReceiveIntentDataScheme() {
        JInvocation getDataSchemeInvocation = JExpr.invoke(getOnReceiveData(), "getIntent").invoke("getScheme");
        onReceiveIntentDataScheme = getOnReceiveBody().decl(getClasses().STRING, "dataScheme", getDataSchemeInvocation);
    }

    /**
     * 在接收方法
     *
     * @return {@link JMethod}
     */
    public JMethod getOnReceiveMethod() {
        if (onReceiveMethod == null) {
            createOnReceive();
        }
        return onReceiveMethod;
    }

    /**
     * 身体上收到
     *
     * @return {@link JBlock}
     */
    public JBlock getOnReceiveBody() {
        if (onReceiveBody == null) {
            createOnReceive();
        }
        return onReceiveBody;
    }

    /**
     * 在接收数据
     *
     * @return {@link JVar}
     */
    public JVar getOnReceiveData() {
        if (onReceiveData == null) {
            createOnReceive();
        }
        return onReceiveData;
    }

    /**
     * 在收到意图行动
     *
     * @return {@link JVar}
     */
    public JVar getOnReceiveIntentAction() {
        if (onReceiveIntentAction == null) {
            setOnReceiveIntentAction();
        }
        return onReceiveIntentAction;
    }

    /**
     * 接收意图数据计划
     *
     * @return {@link JVar}
     */
    public JVar getOnReceiveIntentDataScheme() {
        if (onReceiveIntentDataScheme == null) {
            setOnReceiveIntentDataScheme();
        }
        return onReceiveIntentDataScheme;
    }
}
